
let mouseDown = false;
let mouseWebSocket = null;
let remoteVideoRect;

function mouseInit(ws) {
    mouseWebSocket = ws;

    remoteVideoRect = document.getElementById('screen');
    remoteVideoRect.addEventListener('mousedown', mouseDownHandler);
    remoteVideoRect.addEventListener('mousemove', mouseMoveHandler);
    remoteVideoRect.addEventListener('mouseup', mouseUpHandler);
    remoteVideoRect.addEventListener('wheel', mouseWheelHandler);
    remoteVideoRect.addEventListener('ondragstart', onDragStart);


        remoteVideoRect.addEventListener('touchstart', touchStartHandler);
        remoteVideoRect.addEventListener('touchmove', touchMoveHandler);
        remoteVideoRect.addEventListener('touchend', touchEndHandler);
        remoteVideoRect.addEventListener('touchcancel', touchCancelHandler);
}

function mouseUninit() {
    remoteVideoRect.removeEventListener('ondragstart', onDragStart);
    remoteVideoRect.removeEventListener('wheel', mouseWheelHandler);
    remoteVideoRect.removeEventListener('mouseup', mouseUpHandler);
    remoteVideoRect.removeEventListener('mousemove', mouseMoveHandler);
    remoteVideoRect.removeEventListener('mousedown', mouseDownHandler);

            remoteVideoRect.addEventListener('touchstart', touchStartHandler);
            remoteVideoRect.addEventListener('touchmove', touchMoveHandler);
            remoteVideoRect.addEventListener('touchend', touchEndHandler);
            remoteVideoRect.addEventListener('touchcancel', touchCancelHandler);

    remoteVideoRect = null;
}


function touchStartHandler(event) {
    event.preventDefault(); // 防止默认事件（如页面滚动）
    const touch = event.touches[0];
    // 处理 touchstart 事件，获取触摸点的位置
    console.log('Touch start:', touch.clientX, touch.clientY);
    // 通过 WebSocket 发送手势事件数据
//    mouseWebSocket.send(JSON.stringify({ type: 'touchstart', x: touch.clientX, y: touch.clientY }));
    mouseDown = true;
    mouseHandler(touch, 'down');

}

function touchMoveHandler(event) {
    event.preventDefault();
    const touch = event.touches[0];
    console.log('Touch move1:', touch.clientX, touch.clientY);

//    if (!mouseDown)
//        console.log('Touch mouseDown:', touch.clientX, touch.clientY);
//        return;
//    console.log('Touch move2:', touch.clientX, touch.clientY);
//    if (!isMouseLeftButtonPressed(touch)) {
//        console.log('Touch isMouseLeftButtonPressed:', touch.clientX, touch.clientY);
//        mouseDown = false;
//        mouseHandler(touch, 'up');
//        return;
//    }
    console.log('Touch move3:', touch.clientX, touch.clientY);

    mouseHandler(touch, 'move');
}

function touchEndHandler(event) {
    event.preventDefault();
    const touch = event.changedTouches[0];
    // 处理 touchend 事件，获取触摸点的位置
    console.log('Touch end:', touch.clientX, touch.clientY);
//    mouseWebSocket.send(JSON.stringify({ type: 'touchend', x: touch.clientX, y: touch.clientY }));
    if (!mouseDown)
        return;
    if (isMouseLeftButtonPressed(touch))
        return;
    mouseDown = false;
    mouseHandler(touch, 'up');
}

function touchCancelHandler(event) {
    event.preventDefault();
    // 处理 touchcancel 事件
    console.log('Touch cancel');
    mouseWebSocket.send(JSON.stringify({ type: 'touchcancel' }));
}


function onDragStart() {
    return false;
}

function mouseDownHandler(e) {
    if (!isMouseLeftButtonPressed(e))
        return;
    mouseDown = true;
    mouseHandler(e, 'down');
}

function mouseMoveHandler(e) {
    if (!mouseDown)
        return;
    if (!isMouseLeftButtonPressed(e)) {
        mouseDown = false;
        mouseHandler(e, 'up');
        return;
    }
    mouseHandler(e, 'move');
}

function mouseUpHandler(e) {
    if (!mouseDown)
        return;
    if (isMouseLeftButtonPressed(e))
        return;
    mouseDown = false;
    mouseHandler(e, 'up');
}

function mouseWheelHandler(e) {
    if (!e.ctrlKey)
        return;
    if (e.deltaY > 0)
        mouseHandler(e, 'zoom_out');
    else if (e.deltaY < 0)
        mouseHandler(e, 'zoom_in');
    e.preventDefault();
}

function isMouseLeftButtonPressed(e) {
    let MOUSE_LEFT_BUTTON_NUMBER = 1;

    return e.buttons === undefined ? e.which === MOUSE_LEFT_BUTTON_NUMBER :
        e.buttons === MOUSE_LEFT_BUTTON_NUMBER;
}

function mouseHandler(e, action) {
    let position = getPosition(e);
    let params = '{type=mouse_' + action + ',x=' + position.x + ',y=' + position.y + '}';
    console.log('Touch '+params);
    sendMouseMessage(params);
}

function getPosition(e) {
    let rect = e.target.getBoundingClientRect();
    let x = e.clientX - rect.left;
    let y = e.clientY - rect.top;

    console.log('Touch '+'x='+x+', '+'y='+y+', '+'rect.left='+rect.left+', '+'rect.top='+rect.top+', ');
    x = Math.round(x * e.target.videoWidth * 1.0 / e.target.clientWidth);
    y = Math.round(y * e.target.videoHeight * 1.0 / e.target.clientHeight);

    return {x, y};
}

function backButtonHandler() {
    buttonHandler('back');
}

function homeButtonHandler() {
    buttonHandler('home');
}

function recentButtonHandler() {
    buttonHandler('recent');
}

function powerButtonHandler() {
    buttonHandler('power');
}

function lockButtonHandler() {
    buttonHandler('lock');
}

function buttonHandler(button) {
    sendMouseMessage('{type=button_' + button + '}');
}

function sendMouseMessage(message) {
    if (mouseWebSocket == null)
        return;

    mouseWebSocket.send(message);
}


